import 'package:flutter/material.dart';
import 'package:kxy_flutter_app/components/empty_widget.dart';
import 'package:kxy_flutter_app/components/loading_widget.dart';
import 'package:kxy_flutter_app/components/refresh_footer.dart';
import 'package:kxy_flutter_app/components/refresh_header.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/news.dart';
import 'package:kxy_flutter_app/model/news_category.dart';
import 'package:kxy_flutter_app/view/news/news_item_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class NewsListWidget extends StatefulWidget {
  final NewsCategory category;

  const NewsListWidget({Key key, this.category}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return NewsListWidgetState();
  }
}

class NewsListWidgetState extends State<NewsListWidget> with AutomaticKeepAliveClientMixin {
  int pageIndex = 1;
  int totalCount = 0;
  List<News> newsList = new List<News>();
  RefreshController refreshController = new RefreshController();
  Future loadFuture;

  @override
  void initState() {
    super.initState();
    loadFuture = reload();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return FutureBuilder(
      future: loadFuture,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return body();
        }
        return LoadingWidget();
      },
    );
  }

  Widget body() {
    if (newsList.length == 0) {
      return EmptyWidget(onRefresh: reload);
    }

    return SmartRefresher(
      controller: refreshController,
      enablePullDown: true,
      enablePullUp: true,
      header: RefreshHeader(),
      footer: RefreshFooter(),
      onLoading: () async {
        if (totalCount > newsList.length) {
          await loadMore();
          refreshController.loadComplete();
        } else {
          refreshController.loadNoData();
        }
      },
      onRefresh: () async {
        await reload();
        refreshController.refreshCompleted();
      },
      child: listviewBody(),
    );
  }

  Widget listviewBody() {
    return ListView.builder(
      itemBuilder: (cxt, index) {
        return NewsItemWidget(
          news: newsList[index],
          padding: EdgeInsets.all(15),
          margin: EdgeInsets.only(bottom: 1),
        );
      },
      itemCount: newsList.length,
    );
  }

  @override
  bool get wantKeepAlive => true;

  Future reload() async {
    pageIndex = 0;
    newsList.clear();
    await loadMore();
  }

  Future loadMore() async {
    pageIndex++;
    var res = await Http.instance.post(
      '/news-app/news/getnewslistbycateid',
      params: {
        'page': pageIndex,
        'cateId': widget.category.id,
      },
    );

    if (mounted) {
      setState(() {
        (res.data['list'] as List).forEach((item) {
          var news = News.fromJson(item);
          newsList.add(news);
        });
        totalCount = res.data['totalCount'];
      });
    }
  }
}
